package org.gruposp2p.proyectokarma.gwt.client.ui.user;

import org.gruposp2p.proyectokarma.gwt.client.MainEntryPoint;
import org.gruposp2p.proyectokarma.gwt.client.domain.Peer;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.Response;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.uibinder.client.UiHandler;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.CheckBox;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.LayoutPanel;
import com.google.gwt.user.client.ui.PasswordTextBox;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.VerticalPanel;
import com.google.gwt.user.client.ui.Widget;
import org.gruposp2p.proyectokarma.gwt.client.json.DomainToJSON;
import org.gruposp2p.proyectokarma.gwt.client.ui.ErrorDialog;
import org.gruposp2p.proyectokarma.gwt.client.util.RequestHelper;
import org.gruposp2p.proyectokarma.gwt.client.util.ServerPaths;
import org.gruposp2p.proyectokarma.gwt.client.util.Validator;
import com.google.gwt.json.client.JSONObject;
import com.allen_sauer.gwt.log.client.Log;

public class CreateUserDialog {
	
    interface Style extends CssResource {
        String errorTextBox();
        String textBox();
    }
	
    @UiField DialogBox dialogBox;
    @UiField Style style;
    @UiField VerticalPanel messagePanel;
    @UiField Label messageLabel;
    @UiField TextBox userTextBox;
    @UiField TextBox emailTextBox;
    @UiField PasswordTextBox passwordTextBox;
    @UiField PasswordTextBox repeatPasswordTextBox;
    @UiField Button acceptButton;
    @UiField Button cancelButton;
    @UiField VerticalPanel adminSettingsPanel;
    @UiField VerticalPanel dataPanel;
    @UiField CheckBox enableCheckBox;
    @UiField CheckBox accountExpiredCheckBox;
    @UiField CheckBox accountBlockedCheckBox;
    @UiField CheckBox passwordExpiredCheckBox;
    
    @UiField LayoutPanel sendingDataPanel;
    
    private boolean isAdminSettingsPannelVisible = true;
    
    private static CreateUserDialogUiBinder uiBinder = GWT
                    .create(CreateUserDialogUiBinder.class);

    interface CreateUserDialogUiBinder extends
            UiBinder<Widget, CreateUserDialog> {
    }

    public CreateUserDialog() {
        uiBinder.createAndBindUi(this);
        acceptButton.setStylePrimaryName("acceptButton");
        cancelButton.setStylePrimaryName("cancelButton");
        sendingDataPanel.setVisible(false);
        messagePanel.setVisible(false);
        enableCheckBox.setValue(true);
        adminSettingsPanel.setVisible(isAdminSettingsPannelVisible);
        SubmitHandler sh = new SubmitHandler();
        userTextBox.addKeyDownHandler(sh);
        emailTextBox.addKeyDownHandler(sh);
        passwordTextBox.addKeyDownHandler(sh);
        repeatPasswordTextBox.addKeyDownHandler(sh);
    }

    public void show() {
        dialogBox.center();
        dialogBox.show();
    }
    
	private boolean isValidForm() {
		if (Validator.isTextBoxEmpty(userTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.emptyFieldException());
			userTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			userTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (Validator.isTextBoxEmpty(emailTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.emptyFieldException());
			emailTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			emailTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (!Validator.isValidEmail(emailTextBox.getText())) {
			setMessage(MainEntryPoint.INSTANCE.constants.emailException());
			emailTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			emailTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (Validator.isTextBoxEmpty(passwordTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.emptyFieldException());
			passwordTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			passwordTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (Validator.isTextBoxEmpty(repeatPasswordTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.emptyFieldException());
			repeatPasswordTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			repeatPasswordTextBox.setStyleName(style.errorTextBox(), false);
		}
		if (!Validator.isSamePassword(passwordTextBox, repeatPasswordTextBox)) {
			setMessage(MainEntryPoint.INSTANCE.constants.passwordException());
			passwordTextBox.setStyleName(style.errorTextBox(), true);
			repeatPasswordTextBox.setStyleName(style.errorTextBox(), true);
			return false;
		} else {
			passwordTextBox.setStyleName(style.errorTextBox(), false);
			repeatPasswordTextBox.setStyleName(style.errorTextBox(), false);
		}
		return true;
	}
	
	private void setMessage (String message) {
    	messageLabel.setText(message);
    	messagePanel.setVisible(true);
	}

    @UiHandler("acceptButton")
    void handleAcceptButton(ClickEvent e) {
		if (!isValidForm()) return;
		dialogBox.setVisible(false);
		dialogBox.hide();
		Peer peer = null;
		if (isAdminSettingsPannelVisible) peer = new Peer (userTextBox.getText(), 
				emailTextBox.getText(), passwordTextBox.getText(), emailTextBox.getText());
		else peer = new Peer (userTextBox.getText(), 
				emailTextBox.getText(), passwordTextBox.getText(), emailTextBox.getText(),
				accountExpiredCheckBox.getValue(), accountBlockedCheckBox.getValue(),
				passwordExpiredCheckBox.getValue(), enableCheckBox.getValue());
		JSONObject JSONPeer = DomainToJSON.getPeer(peer);
        //sendingDataPanel.setVisible(true);
		RequestHelper.doPost(ServerPaths.getRegisterPath(), 
				JSONPeer.toString(), new ServerRequestCallback());
		acceptButton.setEnabled(false);
    }
	
    @UiHandler("cancelButton")
    void handleCancelButton(ClickEvent e) {
    	dialogBox.hide();
    }
	
    private class ServerRequestCallback implements RequestCallback {

        @Override
    	public void onError(Request request, Throwable exception) {
        	new ErrorDialog().show("Exception", exception.getMessage());
        	Log.error(exception.getMessage());
    		acceptButton.setEnabled(true);
    	}

        @Override
    	public void onResponseReceived(Request request, Response response) {
			Log.debug("StatusCode: " + response.getStatusCode() + 
					", Response Text: " + response.getText());
    		if (response.getStatusCode() == Response.SC_OK) {
    			//sendingDataPanel.clear();
    			//sendingDataPanel.add(new HTML(response.getText()));
    			Window.alert(response.getText());
    		} else {
    			new ErrorDialog().show("ERROR", "Error (" + response.getStatusCode() + "," 
    					+ response.getStatusText() + ")]");
    		}
    		acceptButton.setEnabled(true);
    	}

    }
    
    private class SubmitHandler implements KeyDownHandler {
		@Override
		public void onKeyDown(KeyDownEvent event) {
			if (KeyCodes.KEY_ENTER == event.getNativeKeyCode()) {
				acceptButton.click();
			}		
		}
	}
    
}